<?php
class admin_controllers_Controller extends Engine_Controller
{
	/**
	 * @var admin_core_Auth
	 */
	protected $_auth;

	/**
	 * @var Engine_Core
	 */
	protected $_core;

	/**
	 * @var Engine_Core_Form
	 */
	protected $_editForm;

	public function preDispatch()
	{
		$this->_authentificate();
	}

	public function initView()
	{
		$this->view = parent::initView();

		$this->view->menu = admin_core_Menu::getInstance()->getCollection($this->_request);

		if (!file_exists(MODULE_PATH . '/views/scripts/' . $this->_request->getControllerName() . '/' . $this->_request->getActionName() . '.phtml')) {
			$this->_helper->getHelper('viewRenderer')->setViewScriptPathSpec(':action.:suffix');
		}

		$this->view
			->headTitle($this->_request->getActionName())
			->headTitle($this->_request->getControllerName())
			->headTitle($this->_request->getModuleName())
			->setSeparator(' / ');

		$this->view->title = $this->_request->getActionName();
		
		return $this->view;
	}

	/**
	 * @return admin_core_Auth
	 */
	protected function getAuth()
	{
		if (empty($this->_auth)) {
			$this->_auth = admin_core_Auth::getInstance();
		}

		return $this->_auth;
	}

	protected function _authentificate()
	{
		if (!$this->getAuth()->isLogged()) {
			$this->_helper->redirector('index', 'auth');
		}
	}

	/**
	 * @param Engine_Core $core
	 * @return void
	 */
	protected function _deleteAction($core = null)
	{
		if (!$id = $this->_request->getParam('id')) {
			$this->addMessage('No entry');
			
			$this->_helper->redirector('index');
		}

		$core = $core ? $core : $this->_core;

		$core->deleteEntryById($id);

		$this->addMessage('Deleted');

		$this->_helper->redirector('index');
	}

	/**
	 * @param Engine_Core_Form $form
	 * @param Engine_Core $core
	 * @return void
	 */
	protected function _editAction($form = null, $core = null)
	{
		$this->_helper->layout()->disableLayout();
		
		$form
			= $form
			? $form
			: (
				  $this->_editForm instanceof Engine_Core_Form
				? $this->_editForm
				: new $this->_editForm
			);

		$core = $core ? $core : $this->_core;

		if ($this->_request->isPost()) {
			$data = $this->_request->getPost();

			if ($form->isValid($data)) {
				$id = $form->save($data);

				$this->addInstantMessage('Saved', 'message');
			}
		}

		if ($id = !empty($id) ? $id : $this->_request->getParam('id')) {
			$form->populate($core->getEntryById($id)->toArray());
		}
		
		$this->view->form = $form;
	}

	/**
	 * @param Engine_Core
	 * @return void
	 */
	protected function _indexAction($core = null)
	{
		$core = $core ? $core : $this->_core;

		$this->view->collection = $core->getCollection();
	}

	public function deleteAction()
	{
		$this->_deleteAction();
	}

	public function editAction()
	{
		$this->_editAction();
	}

	public function indexAction()
	{
		$this->_indexAction();
	}
}